import 'package:flutter/material.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
import 'models.dart';
// import 'package:todos_repository_core/todos_repository_core.dart';

class StateContainer extends StatefulWidget {
  final Widget child;
  final AppState? state;
  final TodosRepository repository;
  const StateContainer({
    super.key,
    required this.child,
    this.state,
    required this.repository,
  });

  @override
  State<StateContainer> createState() => _StateContainerState();

  static _StateContainerState of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<_InheritedStateContainer>()!
        .data;
  }
}

class _StateContainerState extends State<StateContainer> {
  late AppState state;
  VisibilityFilter get activeFilter => state.activeFilter;
  List<Todo> get todos => state.todos.where((todo) {
    if (activeFilter == VisibilityFilter.all) {
      return true;
    } else if (activeFilter == VisibilityFilter.active) {
      return !todo.complete;
    } else {
      return todo.complete;
    }
  }).toList();

  int get completedCount => todos.where((todo) => todo.complete).length;
  int get uncompletedCount => todos.where((todo) => !todo.complete).length;

  void updateVisibilityFilter(VisibilityFilter filter) {
    setState(() {
      state.activeFilter = filter;
    });
  }

  void addTodo(Todo todo) {
    setState(() {
      state.todos.add(todo);
    });
  }

  void updateTodo(
    Todo todo, {
    bool? isCompleted,
    String? id,
    String? note,
    String? task,
  }) {
    setState(() {
      todo.complete = isCompleted ?? todo.complete;
      todo.id = id ?? todo.id;
      todo.note = note ?? todo.note;
      todo.task = task ?? todo.task;
    });
  }

  void clearCompleted() {
    setState(() {
      state.todos.removeWhere((todo) => todo.complete);
    });
  }

  void toggleAll() {
    setState(() {
      todos.forEach((todo) => todo.complete = true);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    if (widget.state != null) {
      state = widget.state!;
    } else {
      state = AppState.loading();
    }
    widget.repository.loadTodos().then((loadedTodos) {
      setState(() {
        state = AppState(todos: loadedTodos.map(Todo.fromEntity).toList());
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    print('building state container=====>>>');
    return _InheritedStateContainer(child: widget.child, data: this);
  }

  void removeTodo(Todo todo) {
    setState(() {
      state.todos.remove(todo);
    });
  }
}

class _InheritedStateContainer extends InheritedWidget {
  final _StateContainerState data;
  const _InheritedStateContainer({required super.child, required this.data});

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }
}
